#线程通信
import time
from multiprocessing import Process,Queue
from threading import Thread,Lock

q = Queue()
n = 20
foot_cont = 0

class Consumer(Thread) :
    def __init__(self,name,time=2):
        super().__init__()
        self.name = f'顾客 %s'% name
        self.time = time


    def run(self):
        self.eat()
    def eat(self):
        global q
        global n
        while n > 0:
            time.sleep(self.time)
            if not q.empty() :
                 food = q.get()
                 if food == None:
                     print('打烊了')
                     break
                 else:
                     print('%s 吃了一个 %s 还剩%s 个' % (self.name,food,q.qsize()) )
                     n -= 1
            else :
                 print('%s过来了，食物没有了 正在做 等一等'% self.name)


class Producer(Thread) :
    def __init__(self,name,count,food,time=1):
        super().__init__()
        #每天生产总个数
        self.count = count;
        self.food  = food
        self.time = time
        #生产者名称
        self.name  = '生产者 %s'% name

    def run(self):
        self.make(self.food)

    def make(self,food):
        global foot_cont
        global q
        i = 0
        while i < self.count and foot_cont < 20:
            time.sleep(self.time)
            mutex.acquire()
            q.put(food)
            i += 1
            foot_cont += 1
            print(f'{self.name}做了第{i}个{food} 现在一共有 {q.qsize()}个食物  累计做了{foot_cont}个')
            mutex.release()
            if i >= 20 :
                print('数量够了 不做了')
                q.put(None)
                break





if __name__ == '__main__' :
   # producer = Producer('zhangsan',5)
   # producer.run('饺子')
   #
   # consumer = Consumer('王二')
   # consumer.run()

   mutex = Lock()
   p1 = Producer('zhangsan',5,'蛋糕')
   p1.start()
   p2 = Producer('李四', 50, '饺子')
   p2.start()
   c1 = Consumer('王二')
   c1.start()
   c2 = Consumer('啊奇')
   c2.start()
   c3 = Consumer('啊奇')
   c3.start()
   p1.join()
   p2.join()
   c1.join()
   c2.join()
   c3.join()

   print('线程结束')





